import $ from "jquery";

export const createBootstrapLayout = (
    data: {
        pages: {
            name: string;
            href: string;
        }[];
        functions: {
            name: string;
            element: () => HTMLElement;
        }[];
    },
    app: JQuery<HTMLDivElement>,
) => {
    // Create layout structure
    const $layout = $(
        `<div class="container-fluid">
            <!-- Header -->
            <header class="row bg-primary text-white p-3">
                <nav class="col-12 d-flex justify-content-center">
                    ${data.pages
                        .map(
                            (page) =>
                                `<a href="${page.href}" class="nav-link text-white me-3">${page.name}</a>`,
                        )
                        .join("")}
                </nav>
            </header>

            <!-- Main Layout -->
            <div class="row" style="min-height: 85vh;">
                <!-- Aside -->
                <aside class="col-md-2 bg-light p-3">
                    <ul class="list-group">
                        ${data.functions
                            .map(
                                (func) =>
                                    `<li class="list-group-item list-group-item-action" data-function-name="${func.name}">
                                        ${func.name}
                                    </li>`,
                            )
                            .join("")}
                    </ul>
                </aside>

                <!-- Content -->
                <main class="col-md-10 bg-white p-3">
                    <div id="content-area">
                        
                    </div>
                </main>
            </div>
        </div>`,
    );

    app.append($layout);

    $layout.find("#content-area").append($(data.functions[0].element()));

    // Bind navigation links
    $layout.find(".nav-link").on("click", function (e) {
        e.preventDefault();
        const href = $(this).attr("href");
        if (href) {
            window.location.href = href;
        }
    });

    // Bind sidebar functions
    $layout.find(".list-group-item").on("click", function () {
        const funcName = $(this).data("function-name");
        const func = data.functions.find((f) => f.name === funcName);

        if (func) {
            const $contentArea = $layout.find("#content-area");
            $contentArea.empty().append(func.element());
        }
    });

    return $layout;
};

export const runMain = (main: (app: JQuery<HTMLDivElement>) => void) => {
    window.$ = $;
    window.onload = () => {
        const app: JQuery<HTMLDivElement> = $("#app");
        main(app);
    };
};
